package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.dto.WeixinLoginResponseDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    JwtProperties jwtProperties;
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";


    @Override
    public UserLoginVO login(UserLoginDTO dto) {
      //调用微信的api获得openid
        Map<String,String>param=new HashMap<>();
        param.put("appid","wx4a715280e54112eb");
        param.put("secret","2bd848dde5725e033271468a64b7f3f3");
        param.put("js_code",dto.getCode());
        param.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN,param);
        log.info("微信登录返回数据 ：{}",json);
        WeixinLoginResponseDTO weixinLoginResponseDTO = JSON.parseObject(json, WeixinLoginResponseDTO.class);
        String openid = weixinLoginResponseDTO.getOpenid();
        //把openid保存到数据库
        log.info("open_id:{}",openid);
        if(!StringUtils.hasLength(openid)){
            throw new BaseException(MessageConstant.LOGIN_FAILED);
        }
        //根据openid查询数据库，判断是否是首次登录，如果是首次就insert
       User user= userMapper.selectByOpenid(openid);
        if (user==null){

            User user1 = new User();
            user1.setOpenid(openid);
            user1.setCreateTime(LocalDateTime.now());
            userMapper.insert(user1);
        }
        //生成jwt_token
        HashMap<String, Object> payload = new HashMap<>();

        payload.put(JwtClaimsConstant.USER_ID,user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(),payload);


        UserLoginVO vo = new UserLoginVO();
        vo.setOpenid(openid);
        vo.setId(user.getId());
        vo.setToken(jwt);
        return vo;




        //把openid保存到数据库
      //生成jwt token



    }
    /**
     * 根据id拿到用户信息
     * 下单
     * */

    @Override
    public User getById(Long currentId) {
        User user= userMapper.getById(currentId);

        return user;
    }
}
